
String.prototype.Trim = function() 
{ 
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 
function validateSalesVolumeTable(tbl){
    if (tbl.rows[0].cells.length != 3){
        return false;
    }
    cell0 = tbl.rows[0].cells[0].getElementsByTagName("span")
    cell1 = tbl.rows[0].cells[1].getElementsByTagName("span")
    cell2 = tbl.rows[0].cells[2].getElementsByTagName("span")

    if (!cell0 || !cell1 || !cell2){
        return false;
    }

    if (cell0[0].innerHTML.Trim() == "日期" &&
        cell1[0].innerHTML.Trim() == "销售量" &&
        cell2[0].innerHTML.Trim() == "销售额(元)"){
        return true;
    }
    return false;
}

function sendoutSalesVolumeData(json){
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:12345/sales", true);

    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            // JSON.parse does not evaluate the attacker's scripts.
            //var resp = JSON.parse(xhr.responseText);
            console.log(xhr.responseText)
        }
    }

    xhr.send(json)
}

function createSalesJsonObject(tbl){

    var jsonStr = "{\"Title\":\"销售简报\", \"Data\":["
    for (var j = 1; j < tbl.rows.length; j++){
        jsonStr += "{\"Date\": \""
        jsonStr += tbl.rows[j].cells[0].childNodes[0].nodeValue,
        jsonStr += "\""
        jsonStr += ", \"Volume\":"
        jsonStr += tbl.rows[j].cells[1].childNodes[0].nodeValue,
        jsonStr += ", \"Yuan\":"
        jsonStr += tbl.rows[j].cells[2].childNodes[0].nodeValue 
        jsonStr += "}"
        if (j < tbl.rows.length -1)
            jsonStr += ","
    }
    jsonStr += "]}"
    return jsonStr
}
//main
console.log("寻找销售简报")
myframe = document.getElementById("SellerDashBoard")
if (myframe){
    window.open(myframe.src)
    return
}


tables = document.getElementsByTagName("table")
console.log("表格个数",tables.length)
found = false
var salesTable
for (var i = 0; i < tables.length; i++){
    if (validateSalesVolumeTable(tables[i])){
        console.log("找到了销售简报")
        salesTable = tables[i]
        salesTable.style.border="thick solid #0000FF";
/*        
        for (var j = 1; j < tables[i].rows.length; j++){
            for (var k = 0; k < tables[i].rows[j].cells.length; k++){
                console.log(tables[i].rows[j].cells[k].childNodes[0].nodeValue)//innerHTML)
            }
        }
*/
        found = true
        break
    }else{
        console.log("表格",i,"不是数据简报");
    }
}
if (!found){
    alert("错误：没有找到销售简报")
}


json = createSalesJsonObject(salesTable)
console.log(json)
sendoutSalesVolumeData(json)

